<?php
ob_start();
if (!file_exists(__DIR__ . '/settings.json') || !file_exists(__DIR__ . '/db.php')) {
    header("Location: /install.php");
    exit;
}
require 'db.php';
if (!isset($_SESSION['user_id'])) {
    header("Location: /login.php");
    exit;
}

$settings_file = __DIR__ . '/settings.json';
$settings = file_exists($settings_file) ? json_decode(file_get_contents($settings_file), true) : [
    'title' => '私人网盘',
    'max_upload_size' => 10 * 1024 * 1024,
    'allowed_file_types' => ['jpg', 'jpeg', 'png', 'pdf', 'txt', 'doc', 'docx'],
    'upload_dir' => 'uploads/',
    'max_files_per_user' => 100
];
$site_title = $settings['title'];
$upload_dir = __DIR__ . '/' . $settings['upload_dir'];

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo "<script>alert('CSRF 验证失败！'); history.back();</script>";
        ob_flush();
        exit;
    }

    $name = $_FILES['file']['name'];
    $tmp = $_FILES['file']['tmp_name'];
    $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
    $user_id = $_SESSION['user_id'];
    $path = $upload_dir . time() . '_' . basename($name);

    $stmt = $conn->prepare("SELECT COUNT(*) as file_count FROM files WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $file_count = $stmt->get_result()->fetch_assoc()['file_count'];
    if ($file_count >= $settings['max_files_per_user']) {
        echo "<script>alert('已达到最大文件数量限制：" . $settings['max_files_per_user'] . "'); history.back();</script>";
        ob_flush();
        exit;
    }

    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if (!in_array($ext, $settings['allowed_file_types'])) {
        echo "<script>alert('不允许的文件类型！仅支持: " . htmlspecialchars(implode(', ', $settings['allowed_file_types'])) . "'); history.back();</script>";
        ob_flush();
        exit;
    }
    if ($_FILES['file']['size'] > $settings['max_upload_size']) {
        echo "<script>alert('文件超过最大限制 " . round($settings['max_upload_size'] / (1024 * 1024), 2) . "MB！'); history.back();</script>";
        ob_flush();
        exit;
    }

    if (!is_dir($upload_dir) && !mkdir($upload_dir, 0755, true)) {
        echo "<script>alert('无法创建上传目录！'); history.back();</script>";
        ob_flush();
        exit;
    }
    if (!is_writable($upload_dir)) {
        echo "<script>alert('上传目录不可写！'); history.back();</script>";
        ob_flush();
        exit;
    }

    if (move_uploaded_file($tmp, $path)) {
        $stmt = $conn->prepare("INSERT INTO files (name, path, user_id, category_id) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssii", $name, $path, $user_id, $category_id);
        if ($stmt->execute()) {
            error_log("File uploaded successfully: " . $path); // 调试日志
            header("Location: /index.php?upload=success"); // 使用绝对路径
            ob_flush();
            exit;
        } else {
            unlink($path);
            echo "<script>alert('数据库错误：" . htmlspecialchars($stmt->error, ENT_QUOTES, 'UTF-8') . "'); history.back();</script>";
            ob_flush();
            exit;
        }
    } else {
        $error = $_FILES['file']['error'];
        echo "<script>alert('文件移动失败，错误码：" . $error . "'); history.back();</script>";
        ob_flush();
        exit;
    }
}

$categories = $conn->query("SELECT id, name FROM categories");
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>上传文件 - <?= htmlspecialchars($site_title) ?></title>
    <link href="/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="<?= $settings['theme'] === 'dark' ? 'bg-dark text-white' : '' ?>">
    <nav class="navbar navbar-expand-lg <?= $settings['theme'] === 'dark' ? 'navbar-dark bg-dark' : 'navbar-light bg-light' ?>">
        <div class="container">
            <a class="navbar-brand" href="index.php"><?= htmlspecialchars($site_title) ?></a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link" href="index.php">首页</a></li>
                    <li class="nav-item"><a class="nav-link" href="upload.php">上传文件</a></li>
                    <li class="nav-item"><a class="nav-link" href="user_center.php">用户中心</a></li>
                    <?php if ($_SESSION['role'] === 'admin'): ?>
                        <li class="nav-item"><a class="nav-link" href="admin/index.php">后台管理</a></li>
                    <?php endif; ?>
                    <li class="nav-item"><a class="nav-link" href="logout.php">退出</a></li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="container py-5">
        <?php if (!empty($settings['announcement'])): ?>
            <div class="alert alert-info"><?= htmlspecialchars($settings['announcement']) ?></div>
        <?php endif; ?>
        <h2>上传文件</h2>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
            <div class="mb-3">
                <label for="file" class="form-label">选择文件（最大 <?= round($settings['max_upload_size'] / (1024 * 1024), 2) ?>MB）</label>
                <input type="file" class="form-control" id="file" name="file" required>
            </div>
            <div class="mb-3">
                <label for="category_id" class="form-label">分类</label>
                <select class="form-select" id="category_id" name="category_id">
                    <option value="">无分类</option>
                    <?php while ($cat = $categories->fetch_assoc()): ?>
                        <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">上传</button>
        </form>
    </div>
    <script src="/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php ob_end_flush(); ?>